package com.chen.utils.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.root.base.R;
import com.chen.utils.entity.DatasourceStrategy;
import com.chen.utils.entity.StrategyInfo;
import com.chen.utils.mapper.DatasourceStrategyMapper;
import com.chen.utils.mapper.StrategyInfoMapper;
import com.chen.utils.params.SaveStrategyParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * 策略配置-前端控制器
 * @author: Long
 * @date: 2023/7/21 22:37
 **/
@Validated
@RestController
@RequestMapping("/strategy")
@Api(tags = "策略配置管理API")
public class StrategyController {

    @Resource
    private StrategyInfoMapper strategyInfoMapper;
    @Resource
    private DatasourceStrategyMapper datasourceStrategyMapper;

    @GetMapping("/list")
    @ApiOperation("获取所有策略配置")
    public R<List<StrategyInfo>> list(){
        return R.ok(strategyInfoMapper.selectList(Wrappers.lambdaQuery()));
    }

    @PostMapping("/save")
    @ApiOperation("保存策略配置")
    public R<StrategyInfo> save(@RequestBody @Validated SaveStrategyParam info){
        StrategyInfo strategy = info.getStrategy();
        if (StrUtil.isNotBlank(strategy.getId())){
            strategyInfoMapper.updateById(strategy);
        }else {
            strategyInfoMapper.insert(strategy);
        }

        Long count = datasourceStrategyMapper.selectCount(
                Wrappers.lambdaQuery(DatasourceStrategy.class)
                        .eq(DatasourceStrategy::getDatasourceId, info.getDatasourceId())
                        .eq(DatasourceStrategy::getStrategyId, strategy.getId())
        );
        if (count == 0){
            DatasourceStrategy ds = new DatasourceStrategy();
            ds.setDatasourceId(info.getDatasourceId());
            ds.setStrategyId(strategy.getId());
            datasourceStrategyMapper.insert(ds);
        }
        return R.ok(strategy,"操作成功!");
    }

    @GetMapping("/delete")
    @ApiOperation("删除策略配置")
    public R<Boolean> delete(@NotBlank(message = "策略配置id不能为空") String id){
        strategyInfoMapper.deleteById(id);
        return R.ok(null,"操作成功!");
    }

    @GetMapping("/getByDatasourceId")
    @ApiOperation("根据数据源id获取策略配置")
    public R<StrategyInfo> getByDatasourceId(String datasourceId){
        DatasourceStrategy ds = datasourceStrategyMapper.selectOne(
                Wrappers.lambdaQuery(DatasourceStrategy.class).eq(DatasourceStrategy::getDatasourceId, datasourceId)
        );
        StrategyInfo info = ds != null ? strategyInfoMapper.selectById(ds.getStrategyId()) : null;
        return R.ok(info);
    }

}
